#!/usr/bin/env python
#coding=utf-8

#******************************************
#This file for XCMD, created by OpenThings.
#Using this to automate the test procedure.
#Author: openthings@163.com. copyright&GPL V2.
#Last modified 2014-11-13.
#******************************************

print("  ==================================================")
print("  * X   X            CCCC   M     M  DDDDDD        *")
print("  *  X X            C       MM   MM   D    D       *")
print("  *   X   >>>>>>>>  C       M M M M   D    D       *")
print("  *  X X            C       M  M  M   D    D       *")
print("  * X   X            CCCC   M     M  DDDDDD        *")
print("  *------------------------------------------------*")
print("  *    Welcome to xConsole--[TCP] via WiFi!        *")
print("  *      For XCMD based ESP8266 SoC.               *")
print("  *     By openthings@163.com. 2014-10.            *")
print("  *------------------------------------------------*")
print("  *     通过网络控制台，远程执行@CMD指令集。       *")
print("  ==================================================")

#============================================
import threading
from socket import *
from time import *

import xcmd_xcon.xc_help
#import xlua_xcon.xc_help

#HOST = '192.168.199.179'
#HOST = '127.0.0.1'
#HOST = '192.168.1.11'
#HOST = '192.168.1.7'
#HOST = '192.168.4.1'
HOST = '192.168.199.236'
#HOST = '192.168.199.146'
#HOST = '192.168.199.192'

#PORT = 8080
PORT = 8268

ADDR = (HOST, PORT) 
addr = (HOST, PORT) 
IS_RUN = 1

print "   Create Client to TCP server..."
tcpClientSock = socket(AF_INET,SOCK_STREAM)
tcpClientSock.connect(ADDR) 

print "   Using TCP at: HOST-",HOST,",PORT-",PORT
print("   \"$\" for HOST, \"@\" for REMOTE,\"EXIT\" for exit. ")
print("  *================================================*")

#============================================
def tcpclient():
	global addr
	while True: 
		if IS_RUN == 0:
			break
		data = tcpClientSock.recv(1024)
		if not data: 
		    break 
		print ">>",data.strip()

def tcpstart():
	t_asocket = threading.Thread(target=tcpclient,args=())
	t_asocket.setDaemon(True)
	t_asocket.start()

#============================================
def exeCMD(strCMD):
	if (strCMD.find("$")==0):	#主机命令。
		strResult = exeHost(strCMD)
		return strResult
	elif(strCMD.find("?")==0):	#主机命令。
		exeHost_help(strCMD)
	else:
		exeRemote(strCMD)	#发送到网络。
		#strResult = tcpClientSock.sendto(strCMD,ADDR)
		#return strResult

def exeRemote(strRemote):
	#tcpClientSock.send(strRemote+'\r\n')	#发送到网络。
	tcpClientSock.send(strRemote)	#发送到网络。
	
#Run CMD at host.	
#执行主机的操作。
def exeHost(strCMD):
	if (strCMD.upper()=="$LOADFILE") or (strCMD.upper()=="$LF"):
		exeHost_lua_upload()
	elif (strCMD.upper()=="$DOFILE") or (strCMD.upper()=="$DF"):
		exeHost_lua_dofile()
	elif (strCMD.upper()=="$LOADTEST"):
		lua_upload("./xlua/hello.lua","hello.lua")
	else:	
		print "Host CMD: ",strCMD
	return "HOSTCMD:",strCMD

#Get Help.
#获取帮助信息。
def exeHost_help(strCMD):
	if (strCMD.upper()=="?XCMD"):
		xcmd_xcon.xc_help.xcmd_list()
	else:
		print "Not find Help doc."
		#xc_help.base_list()
		
#============================================
#loadluafile into nodemcu.
def exeHost_lua_upload():
	luafilehost = raw_input('Input LUA file pathname:') 
	luafileremote = raw_input('Input Remote file name:') 
	lua_upload(luafilehost,luafileremote)

#run a lua file on remote nodemcu.
def exeHost_lua_dofile():
	luafilehost = raw_input('Run LUA file pathname:') 
	lua_dofile(luafilehost)

#============================================
#upload a lua file to remote nodemcu.
def lua_upload(luahost,luaremote):	
	print "Uploading:",luahost,",",luaremote
	print "=========================================="
	luafilehost = open(luahost,'r')
	strRemote = "file.open(\""+luaremote+"\",\"w\")"
	print strRemote
	strResult = exeRemote(strRemote)
	sleep(1)
	for  strlualine in  luafilehost: 
		strlualine = strlualine.strip('\n') 
		strlualine = strlualine.replace("\\","\\\\")
		strlualine = strlualine.replace("\"","\\\"")
		strlualine = "file.writeline(\'"+strlualine+"\')"
		print strlualine
		strLast = exeRemote(strlualine)
		sleep(1)
	strRemote = "file.flush()"
	print strRemote
	exeRemote(strRemote)
	sleep(2)
	strRemote = "file.close()"
	print strRemote
	exeRemote(strRemote)	
	luafilehost.close()
	print "===Upload LUA finished.===================="
	print ""

#run a lua file as dofile() in lua.
#将本地LUA文件在远端运行,通过逐行发送来进行。
def lua_dofile(luahost):	
	print "Remote Run:",luahost
	print "=========================================="
	luafilehost = open(luahost,'r')
	for  strlualine in  luafilehost: 
		print strlualine
		strLast = exeRemote(strlualine)
		sleep(1)
	luafilehost.close()
	print "===Run LUA at remote finished.============"
	print ""
	
#============================================
def waitinput():
	while True: 
		xcmd = raw_input('') 
		if (xcmd.upper()=="EXIT"):
			IS_RUN = 0
			tcpClientSock.close()
			print "[xconsole for wifi] exited."
			exit()
		exeCMD(xcmd)

#============================================
if __name__ == "__main__":
	tcpstart()
	waitinput()

		

